package org.example.netty.service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServerTest {

    public void bind(int port) throws InterruptedException {
        // NioEventLoopGroup 是用来处理I/O操作的多线程事件循环器
        // 第一个经常被叫做‘boss’，用来接收进来的连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // 第二个经常被叫做‘worker’，用来处理已经被接收的连接，一旦‘boss’接收到连接，就会把连接信息注册到‘worker’上
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // ServerBootstrap 是一个启动 NIO 服务的辅助启动类
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    // 设置 socket 的参数选项
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new childChannelHandler());
            // 绑定端口，同步等待成功
            ChannelFuture f = b.bind(port).sync();

            // 等待服务端监听端口关闭
            f.channel().closeFuture().sync();

        } finally {
            // 优雅退出，释放线程资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * ChannelInitializer 是一个特殊的处理类，他的目的是帮助使用者配置一个新的 Channel
     *
     * @author
     */
    private class childChannelHandler extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel arg0) throws Exception {
            arg0.pipeline().addLast(new ServerTestHandler());
        }

    }

    public static void main(String[] args) throws InterruptedException {
        int port = 8888;
        new NettyServerTest().bind(port);
    }

}
